package com.example.thread;

public class BankToGetMoney {

    public static void main(String[] args) {

        Account a = new Account(100,"卡");
        Drawing b = new Drawing(a,2,"小明");
        Drawing c = new Drawing(a,50,"小红");
        Drawing d = new Drawing(a,50,"小黑");

        new Thread(b).start();
        new Thread(c).start();
        new Thread(d).start();

    }

}

class Account
{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public String getName() {
        return name;
    }
}

class Drawing implements Runnable
{

    Account account;
    int drawingMoney;
    int nowMoney;
    String name;

    public Drawing(Account account, int drawingMoney, String name) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (account) {
            if (account.money - drawingMoney < 0) {
                System.out.println(account.name+ "钱不够了   "+"卡剩余"+account.money+"     "+name+"想取"+drawingMoney+"取不了钱了");
                return;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(account.name + "余额为" + account.getMoney());
            System.out.println(name+"想取"+drawingMoney);

            nowMoney = account.getMoney()-drawingMoney;
            account.money = nowMoney;

            System.out.println(name + "取了" + drawingMoney);
            System.out.println("------------------------------");

        }
    }
}
